﻿/**
 * Created by Administrator on 2017/8/18 0018.
 */
var express = require('express');
var crypto = require("crypto");
var qr = require('qr-image')
var jwt = require('jsonwebtoken');
var multer = require("multer");
let path = require('path');
let fs = require('fs');
let moment = require('moment');
var config = require('../config.js');
var db = require('../db/db.js');
var util = require('../util/util.js');
var manage_model = require('../model/manage.js');
var system_dic_model = require('../model/system_dic.js');
var system_jiaose_model = require('../model/system_jiaose.js');
var system_menu_model = require('../model/system_menu.js');


var orders_model = require("../model/orders");


var router = express.Router();
var order = require("./admin/order");
var person = require("./admin/person");
var banner = require("./admin/banner");
var applet = require("./admin/applet");
var goods = require("./admin/goods");
var file = require("./admin/file");

router.use('/order', order);
router.use('/person', person);
router.use('/banner', banner);
router.use('/applet', applet);
router.use('/goods', goods);
router.use('/file', file);

var storagemy = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads');
    },
    filename: function (req, file, cb) {
        var pathstr = path.join(__dirname, "../uploads/" + moment().format('YYYYMMDD'));
        console.log("pathstr", pathstr);
        if (fs.existsSync(pathstr)) {
            cb(null, moment().format('YYYYMMDD') + "/" + `${Date.now()}-${file.originalname}`)

        } else {
            fs.mkdirSync(pathstr);
            cb(null, moment().format('YYYYMMDD') + "/" + `${Date.now()}-${file.originalname}`)
        }


    }
})
var uploadmy = multer({ storage: storagemy });




/**
 * 上传图片
 * @group order_model
 * @route POST /admin/upload/file
 * @summary 上传图片
 * @param {file} imgFile.formData  文件
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 * @security JWT
 */
router.post('/upload/file', uploadmy.single('imgFile'), function (req, res) {
    // 读取上传的图片信息

    console.log(req.file);
    res.json({
        code: 200,
        message: '上传成功',
        pic: config.url + "/uploads/" + req.file.filename,
        file: req.file.filename
    })
})


/**
 * 用户添加
 * @group 管理后台
 * @route POST /admin/manage/add
 * @summary 用户添加
 * @param {string} username.formData 用户名
 * @param {string} password.formData 密码
 * @param {string} jiaoseid.formData 角色
 * @param {string} mid.formData 机构ID
 * @param {string} department.formData 部门
 * @param {string} position.formData 职位
 * @param {string} truename.formData 姓名
 * @param {string} mname.formData 机构名称
 * @param {string} state.formData 是否启用
 * @param {string} issuper.formData 是否超级管理员
 * @param {string} phone.formData 手机号
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/manage/add', async function (req, res) {

    var data = req.body;

    data.password = crypto.createHash("sha1").update(data.password).digest("hex");
    data.createtime = new Date();
    var obj = await manage_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})

/**
 * 用户修改
 * @group 管理后台
 * @route POST /admin/manage/edit
 * @summary 用户修改
 * @param {string} username.formData 用户名
 * @param {string} password.formData 密码
 * @param {string} jiaoseid.formData 角色
 * @param {string} mid.formData 机构ID
 * @param {string} department.formData 部门
 * @param {string} position.formData 职位
 * @param {string} truename.formData 姓名
 * @param {string} mname.formData 机构名称
 * @param {string} state.formData 是否启用
 * @param {string} issuper.formData 是否超级管理员
 * @param {string} phone.formData 手机号
 * @param {string} id.formData 手机号
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/manage/edit", async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    console.log("data", data);
    if (data.userid == '') {
        data.userid = 0;
    }
    if (data.issuper == '') {
        data.issuper = 0;
    }
    var obj = await manage_model.edit(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})
/**
 * 用户列表
 * @group 管理后台
 * 
 * @route POST /admin/manage/list
 * @summary 用户列表
 * @param {string} page.formData  页码从0开始
 * @param {string} rows.formData 行数默认是10
 * @param {string} username.formData 用户名
 * @param {string} jiaoseid.formData 角色
 * @param {string} mid.formData 机构ID
 * @param {string} department.formData 部门
 * @param {string} position.formData 职位
 * @param {string} truename.formData 姓名
 * @param {string} mname.formData 机构名称
 * @param {string} state.formData 是否启用
 * @param {string} issuper.formData 是否超级管理员
 * @param {string} phone.formData 手机号
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/manage/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.mid) != "undefined" && req.body.mid != "") {
        where = where + " and  manage.mid=" + req.body.mid;

    }

    if (typeof (req.body.stime) != "undefined" && typeof (req.body.etime) != "undefined" && req.body.stime != "" && req.body.etime != "") {
        where = where + " and car_nianshen.createtime between '" + req.body.stime + "' and '" + req.body.etime + " 23:59:59'";

    }
    if (typeof (req.body.isdaili) != "undefined" && req.body.isdaili != "") {
        where = where + " and mid!=0";

    }



    console.log("where", where);
    var list = await manage_model.getlist(rows, first, where);
    for (var i = 0; i < list.length; i++) {


        list[i].createtime = moment(list[i].createtime).format("YYYY-MM-DD HH:mm:ss");

        if (list[i].mid != null && list[i].mid != "0") {
            var good = await db.query("select count(*) as num  from yoshop_goods where wxapp_id=" + list[i].mid + " ");
            if (good.length > 0) {
                list[i].goodnum = good[0].num;
            }
        }
        var jiaose = await system_jiaose_model.getinfo("id=" + list[i].jiaoseid);
        if (jiaose.length > 0) {
            list[i].jiaosename = jiaose[0].jiaosename;
        }
    }
    var count = await manage_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});

/**
 * 用户删除
 * @group 管理后台
 * 
 * @route DELETE /admin/manage/del
 * @summary 用户删除
 * @param {string} ids.formData  多个可以用逗号分隔
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.delete('/manage/del', async function (req, res) {

    var where = " id in (" + req.body.ids + ")";
    var obj = await manage_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});
/**
 * 用户详情
 * @group 管理后台
 *
 * @route POST /admin/manage/info
 * @summary 用户详情
 * @param {string} id.formData  
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/manage/info', async function (req, res) {

    var obj = await manage_model.getinfo("id=" + req.body.id);
    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            data: obj[0]
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})



/**
 * 字典添加
 * @group 管理后台
 * 
 * @route POST /admin/dic/add
 * @summary 字典添加
 * @param {string} title.formData 标题
 * @param {string} value.formData 内容
 * @param {string} seq.formData 排序
 * @param {string} content.formData 详细内容
 * @param {string} state.formData 是否启用
 * @param {string} descs.formData 备注
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/dic/add', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    var obj = await system_dic_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})

/**
 * 字典添加
 * @group 管理后台
 * 
 * @route POST /admin/dic/edit
 * @summary 字典修改
 * @param {string} title.formData 标题
 * @param {string} value.formData 内容
 * @param {string} seq.formData 排序
 * @param {string} content.formData 详细内容
 * @param {string} state.formData 是否启用
 * @param {string} descs.formData 备注
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/dic/edit", async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    var obj = await system_dic_model.edit(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})
/**
 * 字典类型
 * @group 管理后台
 * 
 * @route POST /admin/dic/type
 * @summary 字典类型
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/dic/type', async function (req, res) {



    var list = await db.query("select title from system_dic where value is null  group by title ")
    for (var i = 0; i < list.length; i++) {


    }

    res.send({ status: 200, data: list });

});

/**
 * 字典列表
 * @group 管理后台
 * 
 * @route POST /admin/dic/list
 * @summary 字典列表
 * @param {string} page.formData  页码从0开始
 * @param {string} rows.formData 行数默认是10
 * @param {string} title.formData 标题
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/dic/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.title) != "undefined" && req.body.title != "") {
        where = where + " and title='" + req.body.title + "' and value is not null";
    }






    console.log("where", where);
    var list = await system_dic_model.getlist(rows, first, where);
    for (var i = 0; i < list.length; i++) {



    }
    var count = await system_dic_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});
/**
 * 字典删除
 * @group 管理后台
 * 
 * @route DELETE /admin/dic/del
 * @summary 字典删除
 * @param {string} ids.formData  多个可以用逗号分隔
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.delete('/dic/del', async function (req, res) {

    var where = " id in (" + req.body.ids + ")";
    var obj = await system_dic_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});

/**
 * 字典删除分类
 * @group 管理后台
 * 
 * @route DELETE /admin/dic/delbyname
 * @summary 字典删除分类
 * @param {string} title.formData  多个可以用逗号分隔
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.delete('/dic/delbyname', async function (req, res) {

    var where = " title='" + req.body.title + "'";
    var obj = await system_dic_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});
/**
 * 字典详情
 * @group 管理后台
 * 
 * @route POST /admin/dic/info
 * @summary 字典详情
 * @param {string} id.formData 
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/dic/info', async function (req, res) {

    var obj = await system_dic_model.getinfo("id=" + req.body.id);
    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            data: obj[0]
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})


/**
 * 角色添加
 * @group 管理后台
 * 
 * @route POST /admin/jiaose/add
 * @summary 角色添加
 * @param {string} jiaosename.formData 角色名称
 * @param {string} backinfo.formData 备注
 * @param {string} quanxian.formData 权限内容
 * @param {string} state.formData 状态
 * @param {string} mid.formData 机构ID
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/jiaose/add', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    var obj = await system_jiaose_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})
/**
 * 角色修改
 * @group 管理后台
 * 
 * @route POST /admin/jiaose/edit
 * @summary 角色修改
 * @param {string} jiaosename.formData 角色名称
 * @param {string} backinfo.formData 备注
 * @param {string} quanxian.formData 权限内容
 * @param {string} state.formData 状态
 * @param {string} mid.formData 机构ID
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/jiaose/edit", async function (req, res) {

    var data = req.body;
    if (data.mid == "") {
        data.mid = 0;
    }
    var obj = await system_jiaose_model.edit(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})

/**
 * 角色列表
 * @group 管理后台
 * 
 * @route POST /admin/jiaose/list
 * @summary 角色列表
 * @param {string} page.formData  页码从0开始
 * @param {string} rows.formData 行数默认是10
 * @param {string} jiaosename.formData 角色名称
 * @param {string} state.formData 状态
 * @param {string} mid.formData 机构ID
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/jiaose/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.jiaosename) != "undefined" && req.body.jiaosename != "") {
        where = where + " and jiaosename like  '%" + req.body.jiaosename + "%'";

    }

    if (typeof (req.body.state) != "undefined" && req.body.state != "") {
        where = where + " and state=" + req.body.state;


    }



    console.log("where", where);
    var list = await system_jiaose_model.getlist(rows, first, where);
    for (var i = 0; i < list.length; i++) {



    }
    var count = await system_jiaose_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});

/**
 * 角色删除
 * @group 管理后台
 * 
 * @route DELETE /admin/jiaose/del
 * @summary 角色删除
 * @param {string} ids.formData  多个可以用逗号分隔
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.delete('/jiaose/del', async function (req, res) {

    var where = " id in (" + req.body.ids + ")";
    var obj = await system_jiaose_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});
/**
 * 角色详情
 * @group 管理后台
 * 
 * @route POST /admin/jiaose/info
 * @summary 角色详情
 * @param {string} id.formData 
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/jiaose/info', async function (req, res) {

    var obj = await system_jiaose_model.getinfo("id=" + req.body.id);
    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            data: obj[0]
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})
router.post('/getjiaoselist', async function (req, res) {

    var obj = await system_jiaose_model.getinfo("state=1");
    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            data: obj
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})




/**
 * 菜单添加
 * @group 管理后台
 * 
 * @route POST /admin/menu/add
 * @summary 菜单添加
 * @param {string} textstr.formData 菜单名称
 * @param {string} imgurlsrc.formData 图标地址
 * @param {string} valuestr.formData 值
 * @param {string} nvaurl.formData 跳转连接
 * @param {string} parentid.formData 父ID
 * @param {string} seq.formData 排序
 * @param {string} content.formData 内容
 * @param {string} state.formData 是否启用
 * @param {string} datalist.formData 功能
 * @param {string} ishome.formData 是否在首页显示
 * @param {string} ischeck.formData 是否可以选中
 * @param {string} issuper.formData 是否超级管理员
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/menu/add', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    var obj = await system_menu_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})
/**
 * 菜单修改
 * @group 管理后台
 * 
 * @route POST /admin/menu/edit
 * @summary 菜单修改
 * @param {string} textstr.formData 菜单名称
 * @param {string} imgurlsrc.formData 图标地址
 * @param {string} valuestr.formData 值
 * @param {string} nvaurl.formData 跳转连接
 * @param {string} parentid.formData 父ID
 * @param {string} seq.formData 排序
 * @param {string} content.formData 内容
 * @param {string} state.formData 是否启用
 * @param {string} datalist.formData 功能
 * @param {string} ishome.formData 是否在首页显示
 * @param {string} ischeck.formData 是否可以选中
 * @param {string} issuper.formData 是否超级管理员
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/menu/edit", async function (req, res) {

    var data = req.body;
    var obj = await system_menu_model.edit(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})
/**
 * 菜单列表
 * @group 管理后台
 * 
 * @route POST /admin/menu/list
 * @summary 菜单列表
 * @param {string} page.formData  页码从0开始
 * @param {string} rows.formData 行数默认是10
 * @param {string} textstr.formData 菜单名称
 * @param {string} state.formData 是否启用
 * @param {string} parentid.formData 父ID 默认传0
 * @param {string} ishome.formData 是否在首页显示
 * @param {string} ischeck.formData 是否可以选中
 * @param {string} issuper.formData 是否超级管理员
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/menu/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.textstr) != "undefined" && req.body.textstr != "") {
        where = where + " and system_menu.textstr like  '%" + req.body.textstr + "%'";

    }
    if (typeof (req.body.parentid) != "undefined" && req.body.parentid != "") {
        where = where + " and system_menu.parentid=" + req.body.parentid;

    }

    if (typeof (req.body.state) != "undefined" && req.body.state != "") {
        where = where + " and system_menu.state=" + req.body.state;

    }



    console.log("where", where);
    var list = await system_menu_model.getlist(rows, first, where);
    for (var i = 0; i < list.length; i++) {



    }
    var count = await system_menu_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});

/**
 * 菜单删除
 * @group 管理后台
 * 
 * @route DELETE /admin/menu/del
 * @summary 菜单删除
 * @param {string} ids.formData  多个可以用逗号分隔
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.delete('/menu/del', async function (req, res) {
    console.log("ss", req.body, req.query, req.params);
    var where = " id in (" + req.body.ids + ")";
    var obj = await system_menu_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});
/**
 * 菜单详情
 * @group 管理后台
 * 
 * @route POST /admin/menu/info
 * @summary 菜单详情
 * @param {string} id.formData  
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/menu/info', async function (req, res) {

    var obj = await system_menu_model.getinfo("id=" + req.body.id);
    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            data: obj[0]
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})
/**
 * 菜单树
 * @group 管理后台
 * 
 * @route POST /admin/getmenu
 * @summary 菜单树
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/getmenu', async function (req, res) {
    var where = "";



    const rows = await system_menu_model.getinfo("state=1 and parentid=0", "order by seq asc");
    for (var i = 0; i < rows.length; i++) {
        var obj = rows[i];
        var pid = rows[i].id;
        rows[i].label = obj.textstr;


        const rows2 = await system_menu_model.getinfo("state=1 and parentid=" + pid);
        if (rows2.length > 0) {

            for (var j = 0; j < rows2.length; j++) {
                rows2[j].label = rows2[j].textstr;



                if (rows2[j].datalist != "undefined" && rows2[j].datalist != "" && rows2[j].datalist != null) {
                    console.log("rows2[j].datalist", rows2[j].datalist);
                    var arr = JSON.parse(rows2[j].datalist);
                    var list = [];
                    if (arr != null) {
                        for (var k = 0; k < arr.length; k++) {
                            list.push({ id: arr[k].code + "-" + rows2[j].valuestr, label: arr[k].name, valuestr: arr[k].code + "-" + rows2[j].valuestr, pid: rows2[j].id })
                        }
                        rows2[j].children = list;
                    }

                }
            }
        } else {
            if (rows[i].datalist != "undefined" && rows[i].datalist != "" && rows[i].datalist != null) {
                var arr = JSON.parse(rows[i].datalist);
                var list = [];
                if (arr != null) {
                    for (var k = 0; k < arr.length; k++) {
                        list.push({ id: arr[k].code + "-" + rows[i].valuestr, label: arr[k].name, valuestr: arr[k].code + "-" + rows[i].valuestr, pid: rows[i].id })
                    }

                    rows[i].children = list;
                }

            }

        }
        obj.children = rows2;
    }
    var result = {
        "status": "200",
        "message": "success",
        "data": rows
    }
    res.jsonp(result);

});

/**
 * 首页加载菜单接口
 * @group 管理后台
 * @route POST /admin/checkmenu
 * @summary 首页加载菜单接口
 * @param {string} token.formData  
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/checkmenu', async function (req, res) {

    var user = await util.getuserinfo(req.body.token);
    console.log("user", user);
    var jiaose = await system_jiaose_model.getinfo("id=" + user.jiaoseid);

    var quanxian = [];
    if (jiaose.length > 0) {
        console.log("cc", jiaose[0].quanxian, jiaose);
        quanxian = jiaose[0].quanxian.split(",");
    }
    console.log("quanxian", quanxian);
    var arr = [];
    const rows = await system_menu_model.getinfo("state=1 and parentid=0", "order by seq asc");
    for (var i = 0; i < rows.length; i++) {
        var obj = rows[i];
        var pid = rows[i].id;
        rows[i].label = obj.textstr;

        var y = false;
        for (var j = 0; j < quanxian.length; j++) {
            if (rows[i].valuestr == quanxian[j]) {
                y = true;
                break;
            }
        }
        //   y = true;
        if (y) {
            var obj = rows[i];
            obj.children = [];

            const rows2 = await system_menu_model.getinfo("state=1 and parentid=" + pid, " order by seq asc");
            if (rows2.length > 0) {
                var children = [];
                for (var j = 0; j < rows2.length; j++) {
                    rows2[j].label = rows2[j].textstr;

                    var x = false;
                    for (var z = 0; z < quanxian.length; z++) {
                        if (rows2[j].valuestr == quanxian[z]) {
                            x = true;
                            break;
                        }
                    }
                    //x = true;
                    if (x) {
                        children.push(rows2[j]);
                    }



                }
            }

            obj.children = children;
            arr.push(obj);
            children = [];

        }


    }
    var result = {
        "status": "200",
        "message": "success",
        "data": arr
    }
    res.jsonp(result);

});


/**
* 保存配置
* @group 管理后台
* @route POST /admin/config/save
* @summary 保存配置
* @param {string} data.formData   字符串
* @returns {object} 200 - An array of user info
* @returns {Error}  default - Unexpected error
*/
router.post("/config/save", function (req, res) {
    var data = req.body.data;

    var file = path.join(__dirname, '../config/config.json');
    console.log(data);
    fs.writeFileSync(file, data);

    var result = {
        "status": "200",
        "message": "success",
    }
    res.jsonp(result);
});
/**
* 读取配置
* @group 管理后台
* @route POST /admin/config/load
* @summary 读取配置
* @returns {object} 200 - An array of user info
* @returns {Error}  default - Unexpected error
*/
router.post("/config/load", function (req, res) {

    var file = path.join(__dirname, '../config/config.json');
    if (fs.existsSync(file)) {
        var ss = fs.readFileSync(file);
        var str = {};
        if (ss != "") {
            str = JSON.parse(ss);
        }

        var result = {
            "status": 200,
            "data": str,
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": 400,
            "data": "",
        }
        res.jsonp(result);
    }

});


router.post("/getuserinfo", function (req, res) {

    var token = req.body.token;
    jwt.verify(token, config.token.secretOrPrivateKey, async function (err, data) {
        if (err) {
            console.log(err)
            var result = {
                "status": 500,
                "message": "登录过期了"
            }
            res.jsonp(result);
        } else {
            //    console.log("data",data);
            var decode = data;
            var id = decode.id;
            var manage = await db.query("select * from manage where id=" + id);
            if (manage.length > 0) {
                if (manage[0].state == 0) {
                    var result = {
                        "status": 500,
                        "message": "用户已禁用"
                    }
                    res.jsonp(result);
                } else {
                    var result = {
                        "status": 200,
                        "message": "",
                        "data": manage[0]
                    }
                    res.jsonp(result);
                }
            } else {
                var result = {
                    "status": 500,
                    "message": "用户不存在"
                }
                res.jsonp(result);
            }
        }

    })



})



router.post('/vip/add', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();
    var obj = await vip_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})

router.post("/vip/edit", async function (req, res) {

    var data = req.body;
    var obj = await vip_model.edit(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})

router.post('/vip/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.textstr) != "undefined" && req.body.textstr != "") {
        where = where + " and system_menu.textstr like  '%" + req.body.textstr + "%'";

    }
    if (typeof (req.body.parentid) != "undefined" && req.body.parentid != "") {
        where = where + " and system_menu.parentid=" + req.body.parentid;

    }

    if (typeof (req.body.state) != "undefined" && req.body.state != "") {
        where = where + " and system_menu.state=" + req.body.state;

    }



    console.log("where", where);
    var list = await vip_model.getlist(rows, first, where);
    for (var i = 0; i < list.length; i++) {



    }
    var count = await vip_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});


router.delete('/vip/del', async function (req, res) {
    console.log("ss", req.body, req.query, req.params);
    var where = " id in (" + req.body.ids + ")";
    var obj = await vip_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});


router.post('/tj', async function (req, res) {

    var data = {
        paymoney: 0,
        paymoney_day: 0,
        paynum: 0,
        paynum_day: 0,
    }
    var where = "";
    var where2 = "";




    var obj1 = await db.query("select sum(total_fee) as money from orders where pay_status=1 " + where2, []);
    if (obj1.length > 0) {
        data.paymoney = parseInt(obj1[0].money);
    }
    data.paynum = await orders_model.getcount("pay_status=1");

    var obj2 = await db.query("select sum(total_fee) as money from orders where pay_status=1 and  to_days(createtime) = to_days(now()) " + where, []);
    if (obj2.length > 0) {
        data.paymoney_day = parseInt(obj2[0].money);
    }
    data.paynum_day = await orders_model.getcount("pay_status=1 and  to_days(createtime) = to_days(now())");




    var result = {
        "status": "200",
        "message": "success",
        data: data
    }
    res.jsonp(result);

});


router.post('/tj/cate', async function (req, res) {
    var where = "";


    var list = await db.query("SELECT merchant.name,count(*) as num  FROM `orders` join merchant on orders.mid = merchant.id"
        + "  where orders.pay_status=1  group by merchant.name");


    res.send({ status: 200, data: list });
});




router.post('/tj/order', async function (req, res) {

    var where = "";


    var valuelist = [];
    var timelist = [];
    for (var i = 7; i >= 0; i--) {

        var time = moment().subtract(i, "days").format("YYYY-MM-DD");
        timelist.push(time);


        var num = await orders_model.getcount("createtime between '" + time + "' and '" + time + " 23:59:59" + "' and pay_status=1 " + where);


        valuelist.push(num);


    }
    var data = {};
    data.time = timelist;
    data.data = valuelist;

    res.send({ status: 200, data: data });

});

router.post("/updatepass", async function (req, res) {

    var password = crypto.createHash("sha1").update(req.body.password).digest("hex");
    var obj = await db.execute("update manage set password=? where userid=?", [password, req.body.userid]);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "用户未创建"
        }
        res.jsonp(result);
    }

})


module.exports = router;   /*暴露这个 router模块*/